#include <string>
#include <iostream>

#include <Inventor/nodes/SoSeparator.h>
#include <Inventor/nodes/SoCoordinate3.h>
#include <Inventor/nodes/SoFaceSet.h>



#include <QFileDialog>

#include "scenegraph.hpp"
#include "mainwin.hpp"
#include  "stl_parser.hpp"
#include "point.hpp"

using namespace std;




class myparser : public stl_parser
{
public:
myparser(){result=NULL;}
myparser(const char *filename){
	file(string(filename));
	
	result= new SoSeparator;
	result-> ref();
	
	coords=new SoCoordinate3;
	faces=new SoFaceSet;
	result->addChild(coords);
	result->addChild(faces);
	pc=0;
	model::tris.clear();
	model::xmax=-1000;
    model::ymax=-1000;
    model::zmax=-1000;
	
	model::xmin=1000;
    model::ymin=1000;
    model::zmin=1000;
	
	
	}
	
	SoSeparator* Result()
  {
    return result;
  }
  
  
void got_triangle(vector<double>& v)
  {
	
		
       
	point p1(v[0],v[1],v[2]);
    point p2(v[3],v[4],v[5]);
    point p3(v[6],v[7],v[8]);

    triang tri;
    
    
    tri.push_back(p1);
    tri.push_back(p2);
    tri.push_back(p3);
    
 
    
	model::xmax=max(model::xmax,max(p1.x,p2.x,p3.x));
	model::ymax=max(model::ymax,max(p1.y,p2.y,p3.y));
	model::zmax=max(model::zmax,max(p1.z,p2.z,p3.z));

	model::xmin=min(model::xmin,min(p1.x,p2.x,p3.x));
	model::ymin=min(model::ymin,min(p1.y,p2.y,p3.y));
	model::zmin=min(model::zmin,min(p1.z,p2.z,p3.z));

	
    model::tris.push_back(tri);
    
       
    coords->point.set1Value(pc++,v[0],v[1],v[2]);
    coords->point.set1Value(pc++,v[3],v[4],v[5]);
    coords->point.set1Value(pc++,v[6],v[7],v[8]);

    faces->numVertices.set1Value(pc/3-1,3);
    cerr<<".";
    
  }

  long pc;
  SoSeparator *result;
  SoCoordinate3 *coords;
  SoFaceSet *faces;
  
};
	
 
void MainWindow::on_actionOpenModel_activated(){
	QString filename = QFileDialog::getOpenFileName(this, tr("Open model File"),
                                                 "",
                                                 tr("*.stl"));
	
	if(filename.isEmpty())
		return;
		
		cerr<<"file:"<<filename.toAscii().constData()<<endl;
		myparser parser(filename.toAscii().constData());
		scenegraph::root->removeAllChildren();
		scenegraph::root->addChild(parser.Result());
		
		
		parser.parse();
	
	scenegraph::viewer->viewAll();
		
	
	cerr<<"YO!\n";
	}


